# import django
# import os
# import sys
# base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
# sys.path.append(base_dir)
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 's25.settings')
# django.setup()
import time

import pymysql


class S28:
    def __init__(self):
        self.con = pymysql.connect(host='localhost', port=3306, user='root',
                                   password='8852348', database='s28',
                                   charset='utf8')
        self.sor = self.con.cursor()

    def __del__(self):
        self.con.close()
        self.sor.close()

    # 增加数据
    def insert_into(self, table, *args, **kwargs):
        """
        :param table: 添加的表的名字
        :param args:  字典传参 键是代表添加的字段  值代表的是字段的内容
        :param kwargs:
        :return:  没有返回值 创建成功 返回值是错误信息  创建失败
        """
        d = args[0]
        key_list = []
        val_list = []
        for key, val in d.items():
            key_list.append(key)
            val_list.append('"{}"'.format(val))
        # sql = '''insert into %s(%s) values(%s)'''
        # sql = sql % (''.join(table),','.join(key_list), ','.join(val_list))
        sql2 = '''insert into {0} ({1}) values({2})'''.format(''.join(table), ','.join(key_list), ','.join(val_list))
        print('sql2的内容:', sql2)

        self.sor.execute(sql2)
        self.con.commit()

    def select_one(self, a, b, c, d):
        sql = 'select {} from {} where {}=%s'.format(a, b, c)
        print(sql)
        self.sor.execute(sql, (d,))
        ret = self.sor.fetchall()

        # if ret == ():
        #     return None
        # if len(ret[0]) == 1:
        #     return ret[0][0]
        # else:
        return ret

    def py_searche(self, s):
        sql = '{0}'.format(s)
        self.sor.execute(sql)
        ret = self.sor.fetchall()

        return ret

    def py_searche1(self, s):
        sql = '{0}'.format(s)
        self.sor.execute(sql)
        self.con.commit()

    # 查询数据  search('表的名字', {'字段名字':'字段数据','字段2名字':'字段数据'})
    def search(self, table, *args, **kwargs):
        """

        :param table: '表的名字
        :param args: 查询的条件 {'字段名字':'字段数据','字段2名字':'字段数据'})
        :param kwargs:
        :return: 返回一个元组 ((),)
        """
        ret = args[0]
        key = []
        val = []
        sttrs = ''
        for i, j in ret.items():
            key.append(i)
            val.append(j)
        value = val[len(val) - 1]
        for i in range(len(key) - 1):
            if i == 0:
                sttrs += ' {0}="{1}"'.format(key[i], val[i])
            else:
                sttrs += ' and {0}="{1}"'.format(key[i], val[i])
        if len(key) == 1:
            sql = 'select * from {0} where'.format(table) + sttrs + ' {}=%s;'.format(key[len(key) - 1])
        else:
            sql = 'select * from {0} where'.format(table) + sttrs + ' and {}=%s;'.format(key[len(key) - 1])
        # print(val[len(val)-1], type(val[len(val)-1]))
        self.sor.execute(sql, value)
        ret = self.sor.fetchall()
        return ret

    # 修改 uoload('表名字', {'要修改字段的名字':'修改的值', '要修改的名字':'修改的值'}, {'判断条件字段':'条件值', '判断条件字段':'值'})
    def upload(self, table, *args, **kwargs):
        """
        :param table: 表名字
        :param args: 第一个字典是要修改的字段和值 第二个是他的条件
        {'要修改字段的名字':'修改的值', '要修改的名字':'修改的值'}, {'判断条件字段':'条件值', '判断条件字段':'值'})
        :param kwargs:
        :return:  没有返回值
        """
        up = args[0]
        end = args[1]
        up_key = []
        up_val = []
        end_key = []
        end_val = []
        up_str = ''
        end_str = ''
        for i, j in up.items():
            up_key.append(i)
            up_val.append(j)
        for i, j in end.items():
            end_key.append(i)
            end_val.append(j)
        for i in range(len(up_key)):
            if i == 0:
                up_str += '{0}="{1}"'.format(up_key[i], up_val[i])
            else:
                up_str += ' ,{0}="{1}"'.format(up_key[i], up_val[i])
        for i in range(len(end_key) - 1):
            if i == 0:
                end_str += ' {0}="{1}"'.format(end_key[i], end_val[i])
            else:
                end_str += ' and {0}="{1}"'.format(end_key[i], end_val[i])
        if len(end_val) == 1:
            sql = 'update {} set '.format(table) + up_str + end_str + ' where ' + '{0}=%s;'.format(end_key[len(end_key) - 1])
        else:
            sql = 'update {} set '.format(table) + up_str + ' where ' + end_str + ' and {0}=%s;'.format(end_key[len(end_key) - 1])
        print(sql)
        self.sor.execute(sql, end_val[len(end_val) - 1], )
        self.con.commit()

    def delete_use(self, table, *args, **kwargs):
        """S28().delete_use('project', {'id': '9'}) 删除"""
        ret = args[0]
        key = []
        val = []
        sttrs = ''
        for i, j in ret.items():
            key.append(i)
            val.append(j)
        value = val[len(val) - 1]
        for i in range(len(key) - 1):
            if i == 0:
                sttrs += ' {0}="{1}"'.format(key[i], val[i])
            else:
                sttrs += ' and {0}="{1}"'.format(key[i], val[i])
        if len(key) == 1:
            sql = 'delete from {0} where'.format(table) + sttrs + ' {}=%s;'.format(key[len(key) - 1])
        else:
            sql = 'delete from {0} where'.format(table) + sttrs + ' and {}=%s;'.format(key[len(key) - 1])
        # print(val[len(val) - 1], type(val[len(val) - 1]))
        self.sor.execute(sql, value)
        self.con.commit()


# new_time = time.time()+28800
# one_yearsold_time = time.time()+28800+31536000
# array1 = time.gmtime(new_time)
# array2 = time.gmtime(one_yearsold_time)
# dt = time.strftime('%Y-%m-%d %H:%M:%S', array1)
# dt1 = time.strftime('%Y-%m-%d %H:%M:%S', array2)
# print("当前：", dt, type(dt))
# print('一年后', dt1)

import datetime
import time
from datetime import timedelta
#
# ret = S28().py_searche('select start_time,DATE_FORMAT(start_time,"%Y-%m-%d"),'
#                        'count(*) from problem where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(start_time)'
#                        ' GROUP BY start_time')
# print(ret)
#
# li = []
# print(datetime.datetime.now().date())
# for i in ret:
#     one = datetime.datetime.strftime(i[0], '%Y-%m-%d')
#     ime_tuple = time.strptime(i[1], '%Y-%m-%d')
#     li.append([one, int(time.mktime(ime_tuple) * 1000), i[2]])
# print(li)
# import collections
#
# today = datetime.datetime.now().date()
# date_dict = collections.OrderedDict()
# for i in range(0, 30):
#     date = today - datetime.timedelta(days=i)
#     date_dict[date.strftime("%Y-%m-%d")] = [int(time.mktime(date.timetuple()) * 1000), 0]
#
# for i in date_dict:
#
#     for j in li:
#         if i == j[0]:
#             date_dict[i] = [j[1],j[2]]
#
# print(date_dict)
